import { Dictionary } from "../data/Dictionary";

/**
 * 事件管理 
 **/
export class EventManager {
	constructor() { }

	private static dispatcher: egret.EventDispatcher = new egret.EventDispatcher();
	private static funDic: Dictionary = new Dictionary();

    /**
     * 注册自定义监听
     * @param event 事件类型
     * @param cb 监听回调方法
     * @param thisObj 方法作用域
     */
	public static register(type: string, listener: Function, thisObject: any): void {
		this.funDic.add(thisObject.hashCode + "__" + event, listener);
		this.dispatcher.addEventListener(type, listener, thisObject);
	}

    /**
     * 自定义抛事件带参数或者不带
     */
	public static dispatch(event, par = null) {
		this.dispatcher.dispatchEventWith(event, false, par);
	}

    /**
     * 移除自定义监听
     */
	public static unRegister(type: string, listener: Function, thisObject: any): void {
		this.dispatcher.removeEventListener(type, listener, thisObject);
	}

    /**
     * 移除本面板所有的自定义监听 
	 * @param thisObj 必须是显示对象
     */
	public static unRegistersAll(thisObj): void {
		let hasCode = thisObj.hashCode;
		let keys = this.funDic.keys;
		let needRemoveArr = [];
		if (keys && keys.length > 0) {
			for (let i = 0; i < keys.length; i++) {
				let key = keys[i];
				let arr = key.split("__");
				if (parseInt(arr[0]) == hasCode) {
					let cb = this.funDic.get(key);
					this.dispatcher.removeEventListener(arr[1], cb, thisObj);
					cb = null;
					this.funDic.del(key);
				}
			}
		}

	}
}